package net.maku.generator.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.AllArgsConstructor;
import net.maku.generator.common.page.PageResult;
import net.maku.generator.common.query.Query;
import net.maku.generator.common.service.impl.BaseServiceImpl;
import net.maku.generator.entity.GenTemplateTreeEntity;

import net.maku.generator.dao.GenTemplateTreeDao;
import net.maku.generator.service.GenTemplateTreeService;
import net.maku.generator.utils.TreeNode;
import net.maku.generator.utils.TreeUtils;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 代码模板树管理
 *
 * @author 代码小子 codeboy@126.com
 * @since 1.0.0 2024-11-14
 */
@Service
@AllArgsConstructor
public class GenTemplateTreeServiceImpl extends BaseServiceImpl<GenTemplateTreeDao, GenTemplateTreeEntity> implements GenTemplateTreeService {
    @Override
    public PageResult<GenTemplateTreeEntity> page(Query query) {
        IPage<GenTemplateTreeEntity> page = baseMapper.selectPage(
                getPage(query),
                getWrapper(query)
        );

        return new PageResult<>(page.getRecords(), page.getTotal());
        //return new PageResult<>(TreeUtils.build(page.getRecords()), page.getTotal());
    }

    @Override
    public List<GenTemplateTreeEntity> getList() {
        // return baseMapper.selectList(Wrappers.emptyWrapper());
        List<GenTemplateTreeEntity> entityList = baseMapper.selectList(Wrappers.emptyWrapper());
        return TreeUtils.build(entityList);

    }

    @Override
    public boolean save(GenTemplateTreeEntity entity) {
        return super.save(entity);
    }

    @Override
    public List<String> getNameList(List<Long> idList) {
        if (idList.isEmpty()) {
            return null;
        }

        return baseMapper.selectBatchIds(idList).stream().map(GenTemplateTreeEntity::getTemplateName).toList();
    }

    private void getTree(Long id, List<GenTemplateTreeEntity> orgList, List<Long> subIdList) {
        for (GenTemplateTreeEntity org : orgList) {
            if (ObjectUtil.equals(org.getPid(), id)) {
                getTree(org.getId(), orgList, subIdList);

                subIdList.add(org.getId());
            }
        }
    }

}